const Cart=require('../model/cart.model')
const {Op}=require('sequelize')
const Goods=require('../model/goods.model')
class CartService{
    async createOrUpdate(user_id,goods_id){
        let res=await Cart.findOne({
            where:{
             [Op.and]:{
                 user_id,goods_id
             }
            }
        })
        if (res){
            await res.increment('number')
            return await res.reload()
        }else {
            return await Cart.create({
                user_id,goods_id
            })
        }
    }
    async findCarts(user_id){
       const {count,rows}=await Cart.findAndCountAll({
            where:{
                user_id:user_id
            },
           attributes:['id','number','selected'],
           include:{
                model:Goods,
               as:'goods_info'//别名
               //attributes:['id','goods_name']  获取哪些属性
           }
        })
        return{
           total:count,
            list:rows,
            user_id:user_id
        }
    }
    async updateCarts(val){
        const {id,number,selected,user_id}=val
        //目前有待优化，先都传俩参数
        const res=await Cart.update({number:number,selected:selected},{where:{
                user_id:user_id,goods_id:id
            }})
        return res

    }
    async removeCarts(ids,user_id){
        return await Cart.destroy({
            where:{
                goods_id:{
                    [Op.in]:ids
                },
                user_id:user_id
            }
        })

    }
    async selectAllCarts(user_id){
        console.log(user_id)
       return  await Cart.update({
            selected:true
        },{
            where:{
                user_id:user_id
            }
        })

    }
}
module.exports=new CartService()